//
//  JCClubFindVC.m
//  SquashSpark
//
//  Created by 郭吉成 on 2017/11/18.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "JCClubFindVC.h"
#import "JCClubApi.h"
#import "JCClubModel.h"
#import "JCClubFindCell.h"
#import "JCClubInfoVC.h"
#import "ClubsSetting.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "UIScrollView+YFMJRefresh.h"

@interface JCClubFindVC ()<UITableViewDelegate, UITableViewDataSource,UIViewControllerPreviewingDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray <JCClubModel *>*recommendList;
@property (strong, nonatomic) NSMutableArray <JCClubModel *>*clubList;
@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UIButton *searchButton;
@property (weak, nonatomic) IBOutlet UIImageView *headerImageView;
@property (weak, nonatomic) JCClubModel *showClub;
@property (assign, nonatomic) NSInteger pageIndex;
@property (strong, nonatomic) NSArray <JCClubModel *> *searchResultArray;
@property (nonatomic, assign) BOOL isSearching;

@end

@implementation JCClubFindVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initCode];
    [self loadData];
}

- (void)initCode{
    _recommendList = [NSMutableArray array];
    _clubList = [NSMutableArray array];
    _pageIndex = 1;
    [self configRefreshIsSearching:self.isSearching searchText:nil];
    
    __weak typeof(self)weakSelf = self;
    [_tableView addLegendHeaderWithShowTime:NO RefreshingBlock:^{
        weakSelf.pageIndex = 1;
        [weakSelf loadData];
    }];
    [_tableView addNormalFooterWithRefreshingBlock:^{
        [weakSelf loadMore];
    }];
}

- (void)configRefreshIsSearching:(BOOL)isSearching searchText:(NSString *)searchText {
    BOOL showMj_header = YES;
    BOOL showMJ_footer = YES;
    if (isSearching) {
        showMj_header = NO;
        showMJ_footer = searchText.length <= 0;
    }
    _tableView.mj_header.hidden = !showMj_header;
    _tableView.mj_footer.hidden = !showMJ_footer;
}

- (void)setSearchInputText:(NSString *)searchInputText {
    _searchInputText = searchInputText;
    if (_isSearching) {
        [self configRefreshIsSearching:_isSearching searchText:searchInputText];
    }
}

- (void)setSearchResult:(NSArray<JCClubModel *> *)searchResults{
    _searchResultArray = searchResults;
    [_tableView reloadData];
}

- (void)showView{
    if (_recommendList.count > 0) {
        _showClub = _recommendList[arc4random() % _recommendList.count];
        [_headerImageView sd_setImageWithURL:_showClub.banner placeholderImage:kPlaceholdImage];
    }
}

-(void)loadData{
    __weak typeof(self)weakSelf = self;
    if (_isSearching) {
        if ([self.delegate respondsToSelector:@selector(refreashSearchAction:result:)]) {
            [self.delegate refreashSearchAction:self result:^(BOOL success) {
                [weakSelf.tableView.mj_header endRefreshing];
            }];
        }
    }else {
        [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
        [JCClubApi getClubHomeListPage:_pageIndex complete:^(NSError *error, NSArray *recommendClubs, NSArray *clubList) {
            [weakSelf.tableView.mj_header endRefreshing];
            if (error) {
                [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
            }else{
                [weakSelf.hud dismiss];
                [weakSelf.recommendList removeAllObjects];
                [weakSelf.clubList removeAllObjects];
                [weakSelf.recommendList addObjectsFromArray:recommendClubs];
                [weakSelf.clubList addObjectsFromArray:clubList];
                [weakSelf.tableView reloadData];
                [weakSelf showView];
            }
        }];
    }
}

- (void)loadMore{
    __weak typeof(self)weakSelf = self;
    _pageIndex++;
    [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
    [JCClubApi getClubHomeListPage:_pageIndex complete:^(NSError *error, NSArray *recommendClubs, NSArray *clubList)
    {
        [weakSelf.tableView.mj_footer endRefreshing];
        if (error)
        {
            [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
            weakSelf.pageIndex -= 1;
        }
        else
        {
            [weakSelf.hud dismiss];
            if (clubList.count == 0)
            {
                weakSelf.pageIndex -= 1;
                if (weakSelf.isSearching) {
                    weakSelf.searchResultArray = weakSelf.clubList.copy;
                    [weakSelf.tableView reloadData];
                }
                [weakSelf.hud showString:@"No More Data" dimissAfterSecond:1];
            }
            else
            {
                [weakSelf.recommendList removeAllObjects];
                [weakSelf.recommendList addObjectsFromArray:recommendClubs];
                [weakSelf.clubList addObjectsFromArray:clubList];
                if (weakSelf.isSearching) {
                    weakSelf.searchResultArray = weakSelf.clubList.copy;
                }
                else
                {
                    [weakSelf showView];
                }
                [weakSelf.tableView reloadData];
            }
        }
    }];
}

- (void)enterSeachPopKeyBoard:(BOOL)isPop{
    _searchResultArray = _clubList.mutableCopy;
    _isSearching = YES;
    [_tableView reloadData];
    [self configRefreshIsSearching:_isSearching searchText:self.searchInputText];
    if (_delegate && [_delegate respondsToSelector:@selector(didTapSearchAction:popKeyBoard:)]) {
        [_delegate didTapSearchAction:self popKeyBoard:isPop];
    }
    CGRect frame = _headerView.frame;
    frame.size.height = 0;
    _headerView.frame = frame;
    [_tableView beginUpdates];
    [_tableView setTableHeaderView:_headerView];
    [_tableView endUpdates];
    _headerView.alpha = 0;
}

- (IBAction)searchAction:(UIButton *)sender {
    _searchResultArray = _clubList.mutableCopy;
    _isSearching = YES;
    [_tableView reloadData];
    [self configRefreshIsSearching:_isSearching searchText:self.searchInputText];
    if (_delegate && [_delegate respondsToSelector:@selector(didTapSearchAction:popKeyBoard:)]) {
        [_delegate didTapSearchAction:self popKeyBoard:YES];
    }
    CGRect frame = _headerView.frame;
    frame.size.height = 0;
    _headerView.frame = frame;
    [_tableView beginUpdates];
    [_tableView setTableHeaderView:_headerView];
    [_tableView endUpdates];
    _headerView.alpha = 0;
    [self.tabBarController.tabBar setHidden:YES];
}

- (void)quitSearch{
    _searchResultArray = nil;
    _searchInputText = @"";
    _isSearching = NO;
    [self configRefreshIsSearching:_isSearching searchText:_searchInputText];
    [_tableView reloadData];
    _headerView.alpha = 1;
    CGRect frame = _headerView.frame;
    frame.size.height = 266;
    _headerView.frame = frame;
    
    [_tableView beginUpdates];
    [_tableView setTableHeaderView:_headerView];
    [_tableView endUpdates];
     [self.tabBarController.tabBar setHidden:NO];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_searchResultArray == nil) {
        return _clubList.count;
    }else{
        return _searchResultArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    JCClubFindCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([JCClubFindCell class]) forIndexPath:indexPath];
    JCClubModel *model;
    if (_searchResultArray == nil) {
        model = _clubList[indexPath.row];
    }else{
        model = _searchResultArray[indexPath.row];
    }
    [cell setClubModel:model indexPath:indexPath];
    
    if (@available(iOS 9.0, *)) {
        if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
            [self registerForPreviewingWithDelegate:self sourceView:cell];
        } else {
        }
    } else {
    }
    return cell;
}

- (nullable UIViewController *)previewingContext:(id <UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location{

    if (@available(iOS 9.0, *)) {
        NSIndexPath *indexPath = [_tableView indexPathForCell:(UITableViewCell* )[previewingContext sourceView]];
        JCClubModel *model;
        if (_searchResultArray == nil) {
            model = _clubList[indexPath.row];
        }else{
            model = _searchResultArray[indexPath.row];
        }
        
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Clubs" bundle:nil];
        JCClubInfoVC *vc = [storyboard instantiateViewControllerWithIdentifier:NSStringFromClass([JCClubInfoVC class])];
        vc.preferredContentSize = CGSizeMake(0.0f,kYFScreenHeight * 0.8);
        vc.clubID = model.clubID;
        if ([User getUseInfo].joinClubs.count == 0 && [User getUseInfo].adminClubs.count == 0) {
            vc.watchType = WatchClubTypeApplyForAmission;
        }else{
            vc.watchType = WatchClubTypeOtherMember;
        }
        
        CGRect rect = CGRectMake(0, 0, self.view.frame.size.width,[previewingContext sourceView].bounds.size.height);
        previewingContext.sourceRect = rect;
        
        return vc;
    } else {
        
    }
    return nil;
}

- (void)previewingContext:(id <UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit {
    [self showViewController:viewControllerToCommit sender:self];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:kSegueClubInfo]) {
        JCClubModel *model = [sender valueForKey:@"model"];
        JCClubInfoVC *vc = [segue destinationViewController];
        vc.clubID = model.clubID;
        if ([User getUseInfo].joinClubs.count == 0 && [User getUseInfo].adminClubs.count == 0) {
            vc.watchType = WatchClubTypeApplyForAmission;
        }else{
            vc.watchType = WatchClubTypeOtherMember;
        }
        vc.hidesBottomBarWhenPushed = YES;
    }else if ([segue.identifier isEqualToString:kSegueShowClubInfo]){
        JCClubInfoVC *vc = [segue destinationViewController];
        vc.clubID = _showClub.clubID;
        if ([User getUseInfo].joinClubs.count == 0 && [User getUseInfo].adminClubs.count == 0) {
            vc.watchType = WatchClubTypeApplyForAmission;
        }else{
            vc.watchType = WatchClubTypeOtherMember;
        }
        vc.hidesBottomBarWhenPushed = YES;
    }
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}


@end
